#include "GlTriangle.h"

namespace GraphicLibrary
{
	//-------------------------------------------------
	bool Triangle::contains(const Position &pos) const
	{
		float x, y, z;
		getCoordinates(pos, x, y, z);
		return x >= 0.0f && x <= 1.0f
			&& y >= 0.0f && y <= 1.0f
			&& z >= 0.0f && z <= 1.0f;
	}

	//-------------------------------------------------
	void Triangle::getCoordinates(const Position &pos, float &x, float &y, float &z) const
	{
		const float &Ax = mVertexes[0].mX;
		const float &Bx = mVertexes[1].mX;
		const float &Cx = mVertexes[2].mX;
		const float &Ay = mVertexes[0].mY;
		const float &By = mVertexes[1].mY;
		const float &Cy = mVertexes[2].mY;
		const float &Px = pos.mX;
		const float &Py = pos.mY;

		const float down = getDown();
		if(down == 0.0f)
			throw ElInvalidTriangle;

		float up = (Ax - Cx)*(Py - Cy) - (Ay - Cy)*(Px - Cx);
		y = up / down;

		if(Ax - Cx != 0.0f)
			x = (Px - (Bx - Cx)*y - Cx) / (Ax - Cx);
		else if(Ay - Cy != 0.0f)
			x = (Py - (By - Cy)*y - Cy) / (Ay - Cy);
		else
			throw ElInvalidTriangle;
		z = 1 - (x + y);
	}
}
